package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JsonResult;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sessions")
public class SessionController {

    @Autowired
    private IUserService userService;
    /**
     * 登录接口(把session当做资源)
     * 1.资源 /sessions
     * 2.请求方式 post
     * 3.请求参数 邮箱/密码(用户对象接收)
     * 4.返回结果 JsonResult
     */
    @PostMapping
    public JsonResult login(User entity) {
        JsonResult json = new JsonResult();
        try {
            User user = userService.login(entity);
            json.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }
    /**
     * 注销接口
     * 1.资源 /sessions
     * 2.请求方式 delete
     * 3.请求参数 无
     * 4.返回结果 void
     */
    @DeleteMapping
    public void logout() {
        UserContext.getSession().invalidate();
    }
}
